/*
 * qv_testEnvironment.c
 */

#include "qv_testEnvironment.h"
#include "qv_geneticEnvironment.h"
#include "qv_utils.h"
#include "qv_fileIO.h"


void initTestEnvironment(void) {
	int roundNum;

	roundNum = readRoundNum();
	switch (roundNum) {
		case 0:
			/* First thing to do is to create the botfiles for the testbots */
			createTestBotFiles();
			startNextRound(roundNum);
			break;

		case 1:
			/* Spawn the test bots */
			spawnTestBots();
			break;

		default:
			break;
	}
	
	trap_SendConsoleCommand(EXEC_APPEND, "team spectator\n");
	trap_SendConsoleCommand(EXEC_APPEND, "bot_nochat 1\n");
	freeSettings();
}

void updateTestEnvironment(gclient_t *clients) {
	int roundNum = readRoundNum();
	
	startNextRound(roundNum);
	freeSettings();
}


void createTestBotFiles(void) {	
	char *genFileName = malloc(sizeof(char) * LINE_BUF_SIZE);
	char **testBotNames = getTestBotNames();
	
	QV_genData *genData = malloc(sizeof(struct QV_genData) * getSettings()->testbots);
	
	int i;
	for (i = 0; i < getSettings()->testbots; i++) {
		sprintf(genFileName, "%s/%s.ini", QV_TESTBOTS_DIR, testBotNames[i]);
		readGenDataFile(genFileName, i, genData);
		free(testBotNames[i]);
	}

	writeNewBotFiles(genData);
	
	free(genFileName);
	free(testBotNames);
	free(genData);
}

void spawnTestBots(void) {
	int i;
	char **testBotNames = getTestBotNames();
	
	for (i = 0; i < getSettings()->testbots; i++) {
		spawnBot(testBotNames[i]);
		free(testBotNames[i]);
	}

	free(testBotNames);
}
